package com.ht.modules.system.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import com.ht.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;

import com.ht.entity.Result;
import com.ht.query.QueryGenerator;
import com.ht.utils.DicConstants;
import com.ht.modules.system.entity.SysDepart;
import com.ht.modules.system.model.DepartIdModel;
import com.ht.modules.system.model.SysDepartTreeModel;
import com.ht.modules.system.service.ISysDepartService;
import com.ht.modules.system.util.FindsDepartsChildrenUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 部门表 前端控制器
 * <p>
 *
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/sysdepart/sysDepart")
@Slf4j
@Api(tags="部门表")
public class SysDepartController {

    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @GetMapping(value = "/queryTreeList")
    public Result<List<SysDepartTreeModel>> queryTreeList() {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        try {
            List<SysDepartTreeModel> list = sysDepartService.queryTreeList();
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return result;
    }

    /**
     * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
     */
    @PostMapping(value = "/add")
    public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        Result<SysDepart> result = new Result<>();
        String username = JwtUtil.getUserNameByToken(request);
        try {
            sysDepart.setCreateBy(username);
            sysDepartService.saveDepartData(sysDepart, username);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑数据 编辑部门的部分数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        String username = JwtUtil.getUserNameByToken(request);
        sysDepart.setUpdateBy(username);
        Result<SysDepart> result = new Result<>();
        SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
        if (sysDepartEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
            if (ok) {
                result.success("修改成功!");
            }
        }
        return result;
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<SysDepart> delete(@RequestParam(name="id") String id) {
        Result<SysDepart> result = new Result<>();
        SysDepart sysDepart = sysDepartService.getById(id);
        if(sysDepart == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.delete(id);
            if(ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    /**
     * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<SysDepart> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<SysDepart> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysDepartService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
     *
     * @return
     */
    @GetMapping(value = "/queryIdTree")
    public Result<List<DepartIdModel>> queryIdTree() {
        Result<List<DepartIdModel>> result = new Result<>();
        List<DepartIdModel> idList;
        try {
            idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
            if (idList != null && idList.size() > 0) {
                result.setResult(idList);
                result.setSuccess(true);
            } else {
                sysDepartService.queryTreeList();
                idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
                result.setResult(idList);
                result.setSuccess(true);
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.setSuccess(false);
            return result;
        }
    }

    /**
     * <p>
     * 部门搜索功能方法,根据关键字模糊搜索相关部门
     * </p>
     *
     * @param keyWord
     * @return
     */
    @GetMapping(value = "/searchBy")
    public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord") String keyWord) {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        try {
            List<SysDepartTreeModel> treeList = this.sysDepartService.searhBy(keyWord);
            if (treeList == null || treeList.size() == 0) {
                throw new Exception();
            }
            result.setSuccess(true);
            result.setResult(treeList);
            return result;
        } catch (Exception e) {
            e.fillInStackTrace();
            result.setSuccess(false);
            result.setMessage("查询失败或没有您想要的任何数据!");
            return result;
        }
    }


    /**
     * 导出excel
     *
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
        //按字典排序
        Collections.sort(pageList, new Comparator<SysDepart>() {
            @Override
            public int compare(SysDepart arg0, SysDepart arg1) {
                return arg0.getOrgCode().compareTo(arg1.getOrgCode());
            }
        });
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                // orgCode编码长度
                int codeLength = 3;
                List<SysDepart> listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
                //按长度排序
                Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
                    @Override
                    public int compare(SysDepart arg0, SysDepart arg1) {
                        return arg0.getOrgCode().length() - arg1.getOrgCode().length();
                    }
                });
                for (SysDepart sysDepart : listSysDeparts) {
                    String orgCode = sysDepart.getOrgCode();
                    if(orgCode.length() > codeLength) {
                        String parentCode = orgCode.substring(0, orgCode.length()-codeLength);
                        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
                        queryWrapper.eq("org_code", parentCode);
                        try {
                            SysDepart parentDept = sysDepartService.getOne(queryWrapper);
                            if(!parentDept.equals(null)) {
                                sysDepart.setParentId(parentDept.getId());
                            } else {
                                sysDepart.setParentId("");
                            }
                        }catch (Exception e) {
                            //没有查找到parentDept
                        }
                    }else{
                        sysDepart.setParentId("");
                    }
                    sysDepartService.save(sysDepart);
                }
                return Result.ok("文件导入成功！数据行数：" + listSysDeparts.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @GetMapping(value = "/getDepartCodeCount")
    public Result<Integer> getDepartCodeCount(String departCode) {
        Result<Integer> result = new Result<>();
        int counts = sysDepartService.getProjectNameCount(departCode);
        result.setSuccess(true);
        result.setResult(counts);
        return result;
    }

    @GetMapping(value = "/getAllChildDepart")
    @ApiOperation(value="获取所有子单位", notes="获取所有子单位")
    public Result<List<SysDepart>> getAllChildDepart() {
        Result<List<SysDepart>> result = new Result<>();
        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("parent_id");
        queryWrapper.ne("parent_id", "");
        queryWrapper.orderByAsc("org_code");
        List<SysDepart> list = sysDepartService.list(queryWrapper);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    //获取父级部门
    @GetMapping(value = "/getParentDepart")
    public Result<List<Map<String, Object>>> getParentDepart() {
        Result<List<Map<String, Object>>> result = new Result<>();
        LambdaQueryWrapper<SysDepart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepart::getDelFlag, DicConstants.DEL_FLAG_WSC);
        wrapper.eq(SysDepart::getParentId,"").or().isNull(SysDepart::getParentId);
        wrapper.select(SysDepart::getId,SysDepart::getDepartName);
        wrapper.last("order by CONVERT(depart_name using gbk)");
        List<Map<String, Object>> departList = sysDepartService.listMaps(wrapper);
        result.setSuccess(true);
        result.setResult(departList);
        return result;
    }

    /**
     * 获取部门信息用于页面下拉查询
     * @param orgType 部门类型（1-企业；2-部门；不传则企业和部门都会查出来）
     * @return 部门信息list
     */
    @ApiOperation(value="获取部门信息用于页面下拉查询", notes="获取部门信息用于页面下拉查询")
    @GetMapping(value = "/getDepartForSearch")
    public Result<List<Map<String, Object>>> getDepartForSearch(@RequestParam(name="orgType", required=false)String orgType){
        Result<List<Map<String, Object>>> result = new Result<>();
        List<Map<String, Object>> departList = sysDepartService.getDepartForSearch(orgType);
        result.setResult(departList);
        result.success("查询成功！");
        return result;
    }

    @GetMapping(value = "/getLevel1Departs")
    public Result<List<SysDepart>> getLevel1Departs() {
        Result<List<SysDepart>> result = new Result<>();
        result.setResult(sysDepartService.listLevel1Departs());
        result.setSuccess(true);
        return result;
    }

    @GetMapping(value = "/getLevel1DepartByCurrentDepart")
    public Result<List<SysDepart>> getLevel1DepartByCurrentDepart(@RequestParam("departId")String departId) {
        Result<List<SysDepart>> result = new Result<>();
        try{
            result.setResult(sysDepartService.getLevel1DepartByCurrentDepart(departId));
            result.setSuccess(true);
        }catch (Exception e){
            result.error500(e.getMessage());
        }
        return result;
    }
}

